<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://chenjiabing666.github.io/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="code-ltfpVmGDr3" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="杂谈," />





  <link rel="alternate" href="/atom.xml" title="不才陈某技术博客" type="application/atom+xml" />






<meta name="description" content="导读
真是有人(锁)的地方就有江湖(事务)，今天不谈江湖，来撩撩人。
分布式锁的概念、为什么使用分布式锁，想必大家已经很清楚了。前段时间作者写过Redis是如何实现分布式锁，今天这篇文章来谈谈Zookeeper是如何实现分布式锁的。
陈某今天分别从如下几个方面来详细讲讲ZK如何实现分布式锁：
ZK的四种节点
排它锁的实现
读写锁的实现
Curator实现分步式锁



ZK的四种节点
持久性节点：">
<meta property="og:type" content="article">
<meta property="og:title" content="Zookeeper实现分布式锁">
<meta property="og:url" content="https://chenjiabing666.github.io/2020/04/19/Zookeeper实现分布式锁/index.html">
<meta property="og:site_name" content="不才陈某技术博客">
<meta property="og:description" content="导读
真是有人(锁)的地方就有江湖(事务)，今天不谈江湖，来撩撩人。
分布式锁的概念、为什么使用分布式锁，想必大家已经很清楚了。前段时间作者写过Redis是如何实现分布式锁，今天这篇文章来谈谈Zookeeper是如何实现分布式锁的。
陈某今天分别从如下几个方面来详细讲讲ZK如何实现分布式锁：
ZK的四种节点
排它锁的实现
读写锁的实现
Curator实现分步式锁



ZK的四种节点
持久性节点：">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/zk%E6%8E%92%E4%BB%96%E9%94%81.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/%E8%AF%BB%E9%94%81.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/%E5%86%99%E9%94%81.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/%E9%93%BE%E5%BC%8F.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/5.png">
<meta property="og:updated_time" content="2020-04-19T07:49:18.426Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Zookeeper实现分布式锁">
<meta name="twitter:description" content="导读
真是有人(锁)的地方就有江湖(事务)，今天不谈江湖，来撩撩人。
分布式锁的概念、为什么使用分布式锁，想必大家已经很清楚了。前段时间作者写过Redis是如何实现分布式锁，今天这篇文章来谈谈Zookeeper是如何实现分布式锁的。
陈某今天分别从如下几个方面来详细讲讲ZK如何实现分布式锁：
ZK的四种节点
排它锁的实现
读写锁的实现
Curator实现分步式锁



ZK的四种节点
持久性节点：">
<meta name="twitter:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/zk%E6%8E%92%E4%BB%96%E9%94%81.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chenjiabing666.github.io/2020/04/19/Zookeeper实现分布式锁/"/>





  <title>Zookeeper实现分布式锁 | 不才陈某技术博客</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不才陈某技术博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信公众号：码猿技术专栏</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenjiabing666.github.io/2020/04/19/Zookeeper实现分布式锁/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="不才陈某">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不才陈某技术博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Zookeeper实现分布式锁</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-19T15:48:54+08:00">
                2020-04-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/杂谈/" itemprop="url" rel="index">
                    <span itemprop="name">杂谈</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/04/19/Zookeeper实现分布式锁/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/04/19/Zookeeper实现分布式锁/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
		  
		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
			

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="导读"><a href="#导读" class="headerlink" title="导读"></a>导读</h2><ul>
<li>真是有人(<code>锁</code>)的地方就有江湖(<code>事务</code>)，今天不谈江湖，来撩撩人。</li>
<li>分布式锁的概念、为什么使用分布式锁，想必大家已经很清楚了。前段时间作者写过Redis是如何实现分布式锁，今天这篇文章来谈谈Zookeeper是如何实现分布式锁的。</li>
<li>陈某今天分别从如下几个方面来详细讲讲ZK如何实现分布式锁：<ol>
<li><strong>ZK的四种节点</strong></li>
<li><strong>排它锁的实现</strong></li>
<li><strong>读写锁的实现</strong></li>
<li><strong>Curator实现分步式锁</strong></li>
</ol>
</li>
</ul>
<h2 id="ZK的四种节点"><a href="#ZK的四种节点" class="headerlink" title="ZK的四种节点"></a>ZK的四种节点</h2><ul>
<li>持久性节点：节点创建后将会一直存在</li>
<li>临时节点：临时节点的生命周期和当前会话绑定，一旦当前会话断开临时节点也会删除，当然可以主动删除。</li>
<li>持久有序节点：节点创建一直存在，并且zk会自动为节点加上一个自增的后缀作为新的节点名称。</li>
<li>临时有序节点：保留临时节点的特性，并且zk会自动为节点加上一个自增的后缀作为新的节点名称。</li>
</ul>
<h2 id="排它锁的实现"><a href="#排它锁的实现" class="headerlink" title="排它锁的实现"></a>排它锁的实现</h2><ul>
<li>排他锁的实现相对简单一点，利用了<strong>zk的创建节点不能重名的特性</strong>。如下图：</li>
</ul>
<p><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/zk%E6%8E%92%E4%BB%96%E9%94%81.png" alt=""></p>
<ul>
<li>根据上图分析大致分为如下步骤：<ol>
<li>尝试获取锁：创建<code>临时节点</code>，zk会保证只有一个客户端创建成功。</li>
<li>创建临时节点成功，获取锁成功，执行业务逻辑，业务执行完成后删除锁。</li>
<li>创建临时节点失败，阻塞等待。</li>
<li>监听删除事件，一旦临时节点删除了，表示互斥操作完成了，可以再次尝试获取锁。</li>
<li>递归：获取锁的过程是一个递归的操作，<code>获取锁-&gt;监听-&gt;获取锁</code>。</li>
</ol>
</li>
<li><strong>如何避免死锁</strong>：创建的是临时节点，当服务宕机会话关闭后临时节点将会被删除，锁自动释放。</li>
</ul>
<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><ul>
<li>作者参照JDK锁的实现方式加上模板方法模式的封装，封装接口如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * <span class="doctag">@Description</span> ZK分布式锁的接口</div><div class="line"> * <span class="doctag">@Author</span> 陈某</div><div class="line"> * <span class="doctag">@Date</span> 2020/4/7 22:52</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ZKLock</span> </span>&#123;</div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 获取锁</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 解锁</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>模板抽象类如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * <span class="doctag">@Description</span> 排他锁，模板类</div><div class="line"> * <span class="doctag">@Author</span> 陈某</div><div class="line"> * <span class="doctag">@Date</span> 2020/4/7 22:55</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractZKLockMutex</span> <span class="keyword">implements</span> <span class="title">ZKLock</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 节点路径</div><div class="line">     */</div><div class="line">    <span class="keyword">protected</span> String lockPath;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * zk客户端</div><div class="line">     */</div><div class="line">    <span class="keyword">protected</span> CuratorFramework zkClient;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="title">AbstractZKLockMutex</span><span class="params">()</span></span>&#123;&#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AbstractZKLockMutex</span><span class="params">(String lockPath,CuratorFramework client)</span></span>&#123;</div><div class="line">        <span class="keyword">this</span>.lockPath=lockPath;</div><div class="line">        <span class="keyword">this</span>.zkClient=client;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 模板方法，搭建的获取锁的框架，具体逻辑交于子类实现</div><div class="line">     * <span class="doctag">@throws</span> Exception</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">//获取锁成功</span></div><div class="line">        <span class="keyword">if</span> (tryLock())&#123;</div><div class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">"获取锁成功"</span>);</div><div class="line">        &#125;<span class="keyword">else</span>&#123;  <span class="comment">//获取锁失败</span></div><div class="line">            <span class="comment">//阻塞一直等待</span></div><div class="line">            waitLock();</div><div class="line">            <span class="comment">//递归，再次获取锁</span></div><div class="line">            lock();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 尝试获取锁，子类实现</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">()</span> </span>;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 等待获取锁，子类实现</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">waitLock</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 解锁：删除节点或者直接断开连接</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span>  <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>排他锁的具体实现类如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * <span class="doctag">@Description</span> 排他锁的实现类，继承模板类 AbstractZKLockMutex</div><div class="line"> * <span class="doctag">@Author</span> 陈某</div><div class="line"> * <span class="doctag">@Date</span> 2020/4/7 23:23</div><div class="line"> */</div><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ZKLockMutex</span> <span class="keyword">extends</span> <span class="title">AbstractZKLockMutex</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 用于实现线程阻塞</div><div class="line">     */</div><div class="line">    <span class="keyword">private</span> CountDownLatch countDownLatch;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ZKLockMutex</span><span class="params">(String lockPath,CuratorFramework zkClient)</span></span>&#123;</div><div class="line">        <span class="keyword">super</span>(lockPath,zkClient);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 尝试获取锁：直接创建一个临时节点，如果这个节点存在创建失败抛出异常，表示已经互斥了，</div><div class="line">     * 反之创建成功</div><div class="line">     * <span class="doctag">@throws</span> Exception</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">()</span>  </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            zkClient.create()</div><div class="line">                    <span class="comment">//临时节点</span></div><div class="line">                    .withMode(CreateMode.EPHEMERAL)</div><div class="line">                    <span class="comment">//权限列表 world:anyone:crdwa</span></div><div class="line">                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)</div><div class="line">                    .forPath(lockPath,<span class="string">"lock"</span>.getBytes());</div><div class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">        &#125;<span class="keyword">catch</span> (Exception ex)&#123;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 等待锁，一直阻塞监听</div><div class="line">     * <span class="doctag">@return</span>  成功获取锁返回true，反之返回false</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">waitLock</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">//监听节点的新增、更新、删除</span></div><div class="line">        <span class="keyword">final</span> NodeCache nodeCache = <span class="keyword">new</span> NodeCache(zkClient, lockPath);</div><div class="line">        <span class="comment">//启动监听</span></div><div class="line">        nodeCache.start();</div><div class="line">        ListenerContainer&lt;NodeCacheListener&gt; listenable = nodeCache.getListenable();</div><div class="line"></div><div class="line">        <span class="comment">//监听器</span></div><div class="line">        NodeCacheListener listener=()-&gt; &#123;</div><div class="line">            <span class="comment">//节点被删除，此时获取锁</span></div><div class="line">            <span class="keyword">if</span> (nodeCache.getCurrentData() == <span class="keyword">null</span>) &#123;</div><div class="line">                <span class="comment">//countDownLatch不为null，表示节点存在，此时监听到节点删除了，因此-1</span></div><div class="line">                <span class="keyword">if</span> (countDownLatch != <span class="keyword">null</span>)</div><div class="line">                    countDownLatch.countDown();</div><div class="line">            &#125;</div><div class="line">        &#125;;</div><div class="line">        <span class="comment">//添加监听器</span></div><div class="line">        listenable.addListener(listener);</div><div class="line"></div><div class="line">        <span class="comment">//判断节点是否存在</span></div><div class="line">        Stat stat = zkClient.checkExists().forPath(lockPath);</div><div class="line">        <span class="comment">//节点存在</span></div><div class="line">        <span class="keyword">if</span> (stat!=<span class="keyword">null</span>)&#123;</div><div class="line">            countDownLatch=<span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</div><div class="line">            <span class="comment">//阻塞主线程，监听</span></div><div class="line">            countDownLatch.await();</div><div class="line">        &#125;</div><div class="line">        <span class="comment">//移除监听器</span></div><div class="line">        listenable.removeListener(listener);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 解锁，直接删除节点</div><div class="line">     * <span class="doctag">@throws</span> Exception</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        zkClient.delete().forPath(lockPath);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="可重入性排他锁如何设计"><a href="#可重入性排他锁如何设计" class="headerlink" title="可重入性排他锁如何设计"></a>可重入性排他锁如何设计</h3><ul>
<li>可重入的逻辑很简单，在本地保存一个<code>ConcurrentMap</code>，<code>key</code>是当前线程，<code>value</code>是定义的数据，结构如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> ConcurrentMap&lt;Thread, LockData&gt; threadData = Maps.newConcurrentMap();</div></pre></td></tr></table></figure>
<ul>
<li>重入的伪代码如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">()</span></span>&#123;</div><div class="line">    <span class="comment">//判断当前线程是否在threadData保存过</span></div><div class="line">    <span class="comment">//存在，直接return true</span></div><div class="line">    <span class="comment">//不存在执行获取锁的逻辑</span></div><div class="line">    <span class="comment">//获取成功保存在threadData中</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="读写锁的实现"><a href="#读写锁的实现" class="headerlink" title="读写锁的实现"></a>读写锁的实现</h2><ul>
<li>读写锁分为读锁和写锁，区别如下：<ul>
<li>读锁允许多个线程同时读数据，但是在读的同时不允许写线程修改。</li>
<li>写锁在获取后，不允许多个线程同时写或者读。</li>
</ul>
</li>
<li>如何实现读写锁？ZK中有一类节点叫临时有序节点，上文有介绍。下面我们来利用临时有序节点来实现读写锁的功能。</li>
</ul>
<h3 id="读锁的设计"><a href="#读锁的设计" class="headerlink" title="读锁的设计"></a>读锁的设计</h3><ul>
<li>读锁允许多个线程同时进行读，并且在读的同时不允许线程进行写操作，实现原理如下图：</li>
</ul>
<p><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/%E8%AF%BB%E9%94%81.png" alt=""></p>
<ul>
<li>根据上图，获取一个读锁分为以下步骤：<ol>
<li>创建临时有序节点（当前线程拥有的<code>读锁</code>或称作<code>读节点</code>）。</li>
<li>获取路径下所有的子节点，并进行<code>从小到大</code>排序</li>
<li>获取当前节点前的临近写节点(写锁)。</li>
<li>如果不存在的临近写节点，则成功获取读锁。</li>
<li>如果存在临近写节点，对其监听删除事件。</li>
<li>一旦监听到删除事件，<strong>重复2,3,4,5的步骤(递归)</strong>。</li>
</ol>
</li>
</ul>
<h3 id="写锁的设计"><a href="#写锁的设计" class="headerlink" title="写锁的设计"></a>写锁的设计</h3><ul>
<li>线程一旦获取了写锁，不允许其他线程读和写。实现原理如下：</li>
</ul>
<p><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/%E5%86%99%E9%94%81.png" alt=""></p>
<ul>
<li>从上图可以看出唯一和写锁不同的就是监听的节点，这里是监听临近节点(读节点或者写节点)，读锁只需要监听写节点，步骤如下：<ol>
<li>创建临时有序节点（当前线程拥有的<code>写锁</code>或称作<code>写节点</code>）。</li>
<li>获取路径下的所有子节点，并进行<code>从小到大</code>排序。</li>
<li>获取当前节点的临近节点(读节点和写节点)。</li>
<li>如果不存在临近节点，则成功获取锁。</li>
<li>如果存在临近节点，对其进行监听删除事件。</li>
<li>一旦监听到删除事件，<strong>重复2,3,4,5的步骤(递归)</strong>。</li>
</ol>
</li>
</ul>
<h3 id="如何监听"><a href="#如何监听" class="headerlink" title="如何监听"></a>如何监听</h3><ul>
<li>无论是写锁还是读锁都需要监听前面的节点，不同的是读锁只监听临近的写节点，写锁是监听临近的所有节点，抽象出来看其实是一种链式的监听，如下图：</li>
</ul>
<p><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/%E9%93%BE%E5%BC%8F.png" alt=""></p>
<ul>
<li>每一个节点都在监听前面的临近节点，一旦前面一个节点删除了，再从新排序后监听前面的节点，这样递归下去。</li>
</ul>
<h3 id="代码实现-1"><a href="#代码实现-1" class="headerlink" title="代码实现"></a>代码实现</h3><ul>
<li>作者简单的写了读写锁的实现，先造出来再优化，不建议用在生产环境。代码如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ZKLockRW</span>  </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 节点路径</div><div class="line">     */</div><div class="line">    <span class="keyword">protected</span> String lockPath;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * zk客户端</div><div class="line">     */</div><div class="line">    <span class="keyword">protected</span> CuratorFramework zkClient;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 用于阻塞线程</div><div class="line">     */</div><div class="line">    <span class="keyword">private</span> CountDownLatch countDownLatch=<span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</div><div class="line"></div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String WRITE_NAME=<span class="string">"_W_LOCK"</span>;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String READ_NAME=<span class="string">"_R_LOCK"</span>;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ZKLockRW</span><span class="params">(String lockPath, CuratorFramework client)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.lockPath=lockPath;</div><div class="line">        <span class="keyword">this</span>.zkClient=client;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 获取锁，如果获取失败一直阻塞</div><div class="line">     * <span class="doctag">@throws</span> Exception</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">//创建节点</span></div><div class="line">        String node = createNode();</div><div class="line">        <span class="comment">//阻塞等待获取锁</span></div><div class="line">        tryLock(node);</div><div class="line">        countDownLatch.await();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 创建临时有序节点</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     * <span class="doctag">@throws</span> Exception</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">private</span> String <span class="title">createNode</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">//创建临时有序节点</span></div><div class="line">       <span class="keyword">return</span> zkClient.create()</div><div class="line">                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)</div><div class="line">                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)</div><div class="line">                .forPath(lockPath);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 获取写锁</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span>  ZKLockRW <span class="title">writeLock</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ZKLockRW(lockPath+WRITE_NAME,zkClient);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 获取读锁</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span>  ZKLockRW <span class="title">readLock</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ZKLockRW(lockPath+READ_NAME,zkClient);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">tryLock</span><span class="params">(String nodePath)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">//获取所有的子节点</span></div><div class="line">        List&lt;String&gt; childPaths = zkClient.getChildren()</div><div class="line">                .forPath(<span class="string">"/"</span>)</div><div class="line">                .stream().sorted().map(o-&gt;<span class="string">"/"</span>+o).collect(Collectors.toList());</div><div class="line"></div><div class="line"></div><div class="line">        <span class="comment">//第一个节点就是当前的锁，直接获取锁。递归结束的条件</span></div><div class="line">        <span class="keyword">if</span> (nodePath.equals(childPaths.get(<span class="number">0</span>)))&#123;</div><div class="line">            countDownLatch.countDown();</div><div class="line">            <span class="keyword">return</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="comment">//1. 读锁：监听最前面的写锁，写锁释放了，自然能够读了</span></div><div class="line">        <span class="keyword">if</span> (nodePath.contains(READ_NAME))&#123;</div><div class="line">            <span class="comment">//查找临近的写锁</span></div><div class="line">            String preNode = getNearWriteNode(childPaths, childPaths.indexOf(nodePath));</div><div class="line">            <span class="keyword">if</span> (preNode==<span class="keyword">null</span>)&#123;</div><div class="line">                countDownLatch.countDown();</div><div class="line">                <span class="keyword">return</span>;</div><div class="line">            &#125;</div><div class="line">            NodeCache nodeCache=<span class="keyword">new</span> NodeCache(zkClient,preNode);</div><div class="line">            nodeCache.start();</div><div class="line">            ListenerContainer&lt;NodeCacheListener&gt; listenable = nodeCache.getListenable();</div><div class="line">            listenable.addListener(() -&gt; &#123;</div><div class="line">                <span class="comment">//节点删除事件</span></div><div class="line">                <span class="keyword">if</span> (nodeCache.getCurrentData()==<span class="keyword">null</span>)&#123;</div><div class="line">                    <span class="comment">//继续监听前一个节点</span></div><div class="line">                    String nearWriteNode = getNearWriteNode(childPaths, childPaths.indexOf(preNode));</div><div class="line">                    <span class="keyword">if</span> (nearWriteNode==<span class="keyword">null</span>)&#123;</div><div class="line">                        countDownLatch.countDown();</div><div class="line">                        <span class="keyword">return</span>;</div><div class="line">                    &#125;</div><div class="line">                    tryLock(nearWriteNode);</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="comment">//如果是写锁，前面无论是什么锁都不能读，直接循环监听上一个节点即可，直到前面无锁</span></div><div class="line">        <span class="keyword">if</span> (nodePath.contains(WRITE_NAME))&#123;</div><div class="line">            String preNode = childPaths.get(childPaths.indexOf(nodePath) - <span class="number">1</span>);</div><div class="line">            NodeCache nodeCache=<span class="keyword">new</span> NodeCache(zkClient,preNode);</div><div class="line">            nodeCache.start();</div><div class="line">            ListenerContainer&lt;NodeCacheListener&gt; listenable = nodeCache.getListenable();</div><div class="line">            listenable.addListener(() -&gt; &#123;</div><div class="line">                <span class="comment">//节点删除事件</span></div><div class="line">                <span class="keyword">if</span> (nodeCache.getCurrentData()==<span class="keyword">null</span>)&#123;</div><div class="line">                    <span class="comment">//继续监听前一个节点</span></div><div class="line">                    tryLock(childPaths.get(childPaths.indexOf(preNode) - <span class="number">1</span>&lt;<span class="number">0</span>?<span class="number">0</span>:childPaths.indexOf(preNode) - <span class="number">1</span>));</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 查找临近的写节点</div><div class="line">     * <span class="doctag">@param</span> childPath 全部的子节点</div><div class="line">     * <span class="doctag">@param</span> index 右边界</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">private</span> String  <span class="title">getNearWriteNode</span><span class="params">(List&lt;String&gt; childPath,Integer index)</span></span>&#123;</div><div class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; index; i++) &#123;</div><div class="line">            String node = childPath.get(i);</div><div class="line">            <span class="keyword">if</span> (node.contains(WRITE_NAME))</div><div class="line">                <span class="keyword">return</span> node;</div><div class="line"></div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Curator实现分步式锁"><a href="#Curator实现分步式锁" class="headerlink" title="Curator实现分步式锁"></a>Curator实现分步式锁</h2><ul>
<li>Curator是Netflix公司开源的一个Zookeeper客户端，与Zookeeper提供的原生客户端相比，Curator的抽象层次更高，简化了Zookeeper客户端的开发量。 </li>
<li>Curator在分布式锁方面已经为我们封装好了，大致实现的思路就是按照作者上述的思路实现的。中小型互联网公司还是建议直接使用框架封装好的，毕竟稳定，有些大型的互联公司都是手写的，牛逼啊。</li>
<li>创建一个排他锁很简单，如下：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//arg1：CuratorFramework连接对象，arg2：节点路径</span></div><div class="line">lock=<span class="keyword">new</span> InterProcessMutex(client,path);</div><div class="line"><span class="comment">//获取锁</span></div><div class="line">lock.acquire();</div><div class="line"><span class="comment">//释放锁</span></div><div class="line">lock.release();</div></pre></td></tr></table></figure>
<ul>
<li><p>更多的API请参照官方文档，不是此篇文章重点。</p>
</li>
<li><p><strong>至此ZK实现分布式锁就介绍完了，如有想要源码的朋友，老规矩，回复关键词<code>分布式锁</code>获取。</strong></p>
</li>
</ul>
<h2 id="一点小福利"><a href="#一点小福利" class="headerlink" title="一点小福利"></a>一点小福利</h2><ul>
<li>对于Zookeeper不太熟悉的朋友，陈某特地花费两天时间总结了ZK的常用知识点，包括ZK常用shell命令、ZK权限控制、Curator的基本操作API。目录如下：<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/ZK%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/5.png" alt=""></li>
<li><strong>需要上面PDF文件的朋友，老规矩，回复关键词<code>ZK总结</code>。</strong></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>写的可还行？</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.jpg" alt="不才陈某 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
	<div>
	
<div>
      
        
      
</div>

  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/杂谈/" rel="tag"><i class="fa fa-tag"></i> 杂谈</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/19/Zookeeper入门/" rel="next" title="Zookeeper入门">
                <i class="fa fa-chevron-left"></i> Zookeeper入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/20/Mysql最全面试指南/" rel="prev" title="Mysql最全面试指南">
                Mysql最全面试指南 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="不才陈某" />
            
              <p class="site-author-name" itemprop="name">不才陈某</p>
              <p class="site-description motion-element" itemprop="description">本站是不才陈某的技术分享博客。内容涵盖Java后端技术、Spring Boot、微服务架构、系统安全、前端、系统监控等相关的研究与知识分享。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">63</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/1556564194374926" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-globe"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/xiao-ming-64-34-45" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_34162294" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png" target="_blank" title="微信公众号">
                      
                        <i class="fa fa-fw fa-globe"></i>微信公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.pexels.com/zh-cn/" title="Pexels" target="_blank">Pexels</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/" title="纯洁的微笑" target="_blank">纯洁的微笑</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导读"><span class="nav-text">导读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ZK的四种节点"><span class="nav-text">ZK的四种节点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#排它锁的实现"><span class="nav-text">排它锁的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#代码实现"><span class="nav-text">代码实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可重入性排他锁如何设计"><span class="nav-text">可重入性排他锁如何设计</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#读写锁的实现"><span class="nav-text">读写锁的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#读锁的设计"><span class="nav-text">读锁的设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#写锁的设计"><span class="nav-text">写锁的设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何监听"><span class="nav-text">如何监听</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码实现-1"><span class="nav-text">代码实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Curator实现分步式锁"><span class="nav-text">Curator实现分步式锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一点小福利"><span class="nav-text">一点小福利</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">不才陈某</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">143.1k</span>
  
</div>

<!--





  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共143.1k字</span>
</div>

        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'RtlQOgOT3M0hgyMeogykSQjT-gzGzoHsz',
        appKey: 'vSCxLU88wnXVf0Pa8mwJrCPm',
        placeholder: '原创不易，欢迎各位指正',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
